import React from 'react';
import './App.css';
import axios from 'axios';
import './classify.css';
import BScroll from 'better-scroll';

interface TypeProps{
    id:number,
    text:string
}

interface ClassifyProp{
    id:number,
    title:string,
    children:TypeProps[]
}

interface Istate{
    classify:ClassifyProp[]
}

export default class App extends React.Component<{},Istate>{
    state = {
        classify:[]
    }
    scroll: any;
    box: HTMLDivElement | null| undefined;

    componentDidMount(){

        //选中DOM中定义的 .wrapper 进行初始化
        this.scroll = new BScroll('.right', {
            click: true,  // better-scroll 默认会阻止浏览器的原生 click 事件
            scrollY: true, //关闭竖向滚动
        })
        
        axios.get('/api/types',{data:{id:1}}).then(res => {
            this.setState({
                classify:res.data
            },() => {
                this.scroll.refresh()
            })
        })
       
    }

    render() {
        let {classify} = this.state;
        return (
            <div className="wrapper">
                <div className="left">
                    <ul>
                        {classify.map((item:ClassifyProp,index:number) => <li key={item.id} onClick={()=>this.scrollTo(index)}>{item.title}</li>)}
                    </ul>
                </div>
                <div className="right">
                    <div ref={box => this.box=box}>
                        {classify.map((item:ClassifyProp) => <div key={item.id}>
                            <h6>{item.title}</h6>
                            <ul className="types">
                                {item.children.map((v:TypeProps) => <li key={v.text}>{v.text}</li>)}
                            </ul>
                        </div>)}
                    </div>
                </div>
            </div>
        )
    }

    scrollTo = (index:number) => {
        this.scroll.scrollToElement((this.box as HTMLDivElement).children[index],0,0,0)
    }
}

